package aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Random;

@Aspect
@Component
public class OrderAspect {
    // 定义切点，匹配OrderService接口中的所有方法
    @Pointcut("execution(* service.OrderService.*(..))")
    public void orderPointcut() {}

    // 1. 前置增强：对add, delete, find方法生效
    @Before("orderPointcut()")
    public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println("hello, 我是一个前置增强");
    }

    // 2. 后置增强：仅对add, delete方法生效
    @AfterReturning("execution(* service.OrderService.add(..)) || execution(* service.OrderService.delete(..))")
    public void afterReturningAdvice() {
        System.out.println("bye, 我是一个后置增强");
    }

    // 3. 获取返回值：对所有方法生效
    @AfterReturning(pointcut = "orderPointcut()", returning = "result")
    public void afterReturningWithResult(JoinPoint joinPoint, Object result) {
        System.out.println("方法 " + joinPoint.getSignature().getName() + " 返回值：" + result);
    }

    // 4. 计算执行时间：对所有方法生效
    @Around("orderPointcut()")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        long endTime = System.currentTimeMillis();
        System.out.println("方法 " + proceedingJoinPoint.getSignature().getName() +
                " 执行时间：" + (endTime - startTime) + " 毫秒");
        return result;
    }

    // 5. 权限校验：仅对add, delete方法生效
    @Around("execution(* service.OrderService.add(..)) || execution(* service.OrderService.delete(..))")
    public Object checkPermission(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Random random = new Random();
        int permission = random.nextInt(2); // 0表示有权限，1表示无权限

        if (permission == 0) {
            System.out.println("有权限，执行方法");
            return proceedingJoinPoint.proceed();
        } else {
            System.out.println("无权限，终止方法执行");
            return null;
        }
    }
}